package com.txm.controller;

import common.enumenumeration.Event;
import common.enumenumeration.MsgType;
import common.model.weixin.Message;
import common.model.weixin.message.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by Administrator on 2016/7/31.
 */
@Controller
@RequestMapping("weixin")
public class WeiXinController extends BaseController {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @RequestMapping(value = "weixin.do", method = RequestMethod.GET)
    public void weixinGet(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        String signature = httpServletRequest.getParameter("signature");
        String timestamp = httpServletRequest.getParameter("timestamp");
        String nonce = httpServletRequest.getParameter("nonce");
        String echostr = httpServletRequest.getParameter("echostr");
        PrintWriter pw = httpServletResponse.getWriter();
        String[] strs = {redisTemplate.opsForHash().get("properties", "token").toString(), nonce, timestamp};
        Arrays.sort(strs);
        StringBuffer sb = new StringBuffer();
        for (String string : strs) {
            sb.append(string);
        }
        String s = DigestUtils.sha1Hex(sb.toString());
        if (s.equals(signature)) {
            pw.print(echostr);
        }
        IOUtils.closeQuietly(pw);
    }

    @RequestMapping(value = "weixin.do", method = RequestMethod.POST)
    @ResponseBody
    public Message weixinPost(Model model, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, @RequestBody Message message) throws IOException, JAXBException {
        // 发送时间
        message.setCreateTime(System.currentTimeMillis());
        // 发送人和接受人交换
        String temToUserName = message.getToUserName();
        message.setToUserName(message.getFromUserName());
        message.setFromUserName(temToUserName);
        if (message.getMsgType() == MsgType.text) {
            if ("image".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.image);
                Image image = new Image();
                image.setMediaId("O3BgMsNYwG7ERnnXTp28qqUGZpqDpkeLbLdJdwg3jMIWPaVLNKHvouDmO5Wd4qLQ");
                message.setImage(image);
            } else if ("music".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.music);
                Music music = new Music();
                music.setThumbMediaId("cIB7znE0VCwxwBR8pCCDGkv8LtaLvSp8HS4hi5LIXHNtJ1bvwif_9eyxAVdVJv1U");
                music.setTitle("see you again");
                music.setDescription("速7片尾曲");
                music.setMusicUrl("http://tangxinmao.yicp.io/resources/music/See You Again.mp3");
                music.setHQMusicUrl("http://tangxinmao.yicp.io/resources/music/See You Again.mp3");
                message.setMusic(music);
            } else if ("video".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.video);
                Video video = new Video();
                video.setTitle("see you again");
                video.setDescription("速7片尾曲");
                video.setMediaId("MmYMN0ME8F2h1wx6g6Ry71A7QFFfEEwFoEtvig98mn2QKXvNaQcN8tOda-gjPI56");
                message.setVideo(video);
            } else if ("voice".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.voice);
                Voice voice = new Voice();
                voice.setMediaId("toW3hMzyjWqIIszpkD3mVwK4nkKljo3acPNcWG0SDYHYyN-IAZ-I0qgomzFZT6D_");
                message.setVoice(voice);
            } else if ("news".equalsIgnoreCase(message.getContent())) {
                message.setMsgType(MsgType.news);
                Item i = new Item();
                i.setDescription("回复image 或者 news");
                i.setPicUrl("http://tangxinmao.yicp.io/resources/image/006.png");
                i.setTitle("该账号仅用于测试！");
                i.setUrl("http://tangxinmao.yicp.io");
                List<Item> l = new ArrayList<Item>();
                l.add(i);
                message.setArticles(l);
                message.setArticleCount(l.size());
            }
        }
        if (message.getMsgType() == MsgType.event) {
            if (message.getEvent() == Event.subscribe) {
                message.setMsgType(MsgType.news);
                Item i = new Item();
                i.setDescription("回复image 或者 news");
                i.setPicUrl("http://tangxinmao.yicp.io/resources/image/006.png");
                i.setTitle("该账号仅用于测试！");
                i.setUrl("http://tangxinmao.yicp.io");
                List<Item> l = new ArrayList<Item>();
                l.add(i);
                message.setArticles(l);
                message.setArticleCount(l.size());

            } else if (message.getEvent() ==
                    Event.unsubscribe) {
                message.setMsgType(MsgType.text);
                message.setContent("下次再来额！");
            } else if (message.getEvent() == Event.CLICK) {
                message.setMsgType(MsgType.text);
                message.setContent("欢迎光林！");
            } else if (message.getEvent() == Event.VIEW) {
            } else if (message.getEvent() == Event.scancode_push) {


            }

        }
        if (message.getMsgType() == MsgType.location) {
            message.setMsgType(MsgType.text);
            message.setContent(message.getLabel());
        }
        return message;
    }

}
